package com.sky.controller.user;

import com.sky.context.BaseContext;
import com.sky.entity.AddressBook;
import com.sky.result.Result;
import com.sky.service.AddressBookService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Delete;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Slf4j
@RestController
@RequestMapping("/user/addressBook")
@Api(tags = "导入地址功能代码")
public class AddressBookController {
    @Autowired
    private AddressBookService addressBookService;

    /**
     * 新增地址
     * @param addressBook
     * @return
     */
    @PostMapping
    @ApiOperation("新增地址")
    public Result  save(@RequestBody AddressBook addressBook){

        addressBookService.save(addressBook);
        return  Result.success();
    }

    /**
     * 查询所有的地址
     * @return
     */
    @GetMapping("/list")
    @ApiOperation("查询当前登陆用户的所有的地址信息")
    public  Result <List<AddressBook>>selectAddress(){

        AddressBook addressBook = new AddressBook();
        addressBook.setUserId(BaseContext.getCurrentId());
      List<AddressBook>  list= addressBookService.selectAddress(addressBook);
      return Result.success(list);
    }

    /**
     * 查询默认的地址
     * @return
     */
    @GetMapping("/default")
    @ApiOperation("查询默认地址")
    public Result <AddressBook> selectDefaultAddress(){
        AddressBook addressBook = new AddressBook();
        addressBook.setIsDefault(1);

        addressBook.setUserId(BaseContext.getCurrentId());
        List<AddressBook> list = addressBookService.selectAddress(addressBook);
        if (!CollectionUtils.isEmpty(list) && list.size()>0){
            return Result.success(list.get(0));
        }
        return Result.error("没有查到默认地址");

    }

    /**
     * 根据id修改地址
     * @param addressBook
     * @return
     */
    @PutMapping
    @ApiOperation("根据id修改地址")
    public Result update(@RequestBody AddressBook addressBook){
        addressBookService.update(addressBook);
        return Result.success();
}

    /**
     * 根据id删除地址
     * @param id
     * @return
     */
    @DeleteMapping
    @ApiOperation("根据id删除地址")
public  Result deleteAddress( Long id){
        addressBookService.deleteAddress(id);
        return Result.success();

}

    /**
     * 根据id查询地址
     * @param id
     * @return
     */
    @GetMapping("{id}")
@ApiOperation("根据id查询地址")
public  Result<AddressBook> selectById(@PathVariable Long id){

       AddressBook addressBook= addressBookService.selectById(id);
       return Result.success(addressBook);

}

    /**
     * 设置默认地址
     * @return
     */
    @PutMapping("/default")
@ApiOperation("设置默认地址")
public  Result setDefault(@RequestBody AddressBook addressBook){
        addressBookService.setDefault(addressBook);
        return Result.success();


}


}
